package com.cubesugar2014.carechild;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.cubesugar2014.carechild.MainActivity.PlaceholderFragment;

import com.klinker.android.send_message.Message;
import com.klinker.android.send_message.Settings;
import com.klinker.android.send_message.Transaction;

import android.app.ActivityManager;
import android.app.ActivityManager.RecentTaskInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Notification.BigPictureStyle;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.graphics.Bitmap.CompressFormat;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.PreviewCallback;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.Browser;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.NotificationCompat;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.format.Time;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class SService extends Service implements LocationListener {

	
	static public void FLOG(String text)
	{       
	   File logFile = new File("sdcard/log.txt");
	   if (!logFile.exists())
	   {
	      try
	      {
	         logFile.createNewFile();
	      } 
	      catch (IOException e)
	      {
	         // TODO Auto-generated catch block
	         e.printStackTrace();
	      }
	   }
	   try
	   {
	      //BufferedWriter for performance, true to set append to file flag
	      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
	      buf.append(text);
	      buf.newLine();
	      buf.flush();
	      buf.close();
	   }
	   catch (IOException e)
	   {
	      // TODO Auto-generated catch block
	      e.printStackTrace();
	   }
	}
	
	public static final String PREFS_NAME = "CChildPrefsFile";

    private NotificationManager  mManager; 
	private Notification.Builder mBuilder;
	
	static public boolean mOnWorking = false;
    private SharedPreferences mSettings;
	
    private static Timer timer = new Timer(); 
    
    private long mActivateTick;
    
    
	private SensorManager sensorManager;
	private AccListener listen;
	
	LocationManager locationManager;

	private ConnectivityManager mConnMgr;
	private PowerManager.WakeLock mWakeLock;
	

	private final int FREQUENCY = 44100;//11025;
	private final int CUSTOM_FREQ_SOAP = 1;
	private final int OUT_FREQUENCY = FREQUENCY * CUSTOM_FREQ_SOAP;
	private final int CHANNEL_CONTIGURATION = AudioFormat.CHANNEL_IN_MONO;
	private final int AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT; 

	private static boolean isRecording;
	private int bufferSize;
	private AudioRecord audioRecord; 
	
	private double maxAmp;
	
	
	static float accX = 0.0f;
 	static float accY = 0.0f;
 	static float accZ = 0.0f;
 	 	
	private class AccListener implements SensorEventListener {
		 
		 	public float maxM = 0;
		 	public Context context;
		 	
		 	private final int THRESHOLD = 30;//11025;
		    
		 	private long preEventTime;
		 	AudioRecorder recorder;

		 
		 	
			public float magnitude(float[] vector) {
			    return (float) Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]
			        + vector[2] * vector[2]);
			  }
			
			public boolean _acquiredAudio(String fileName) {  
				
				
				
				recorder = new AudioRecorder(fileName);
	           	
            	try {
            	 	recorder.start();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					Toast.makeText(context,
	            			"recorder IOException"
							,Toast.LENGTH_LONG).show(); 
					e1.printStackTrace();
				}
            	
				Handler handler = new Handler(); 
                
				handler.postDelayed(new Runnable() 
				{ 
                	public void run()
                	{ 
                	
                		try {
        	        		 recorder.stop();
        	        	} catch (IOException e) 
        	        	
        	        	{
     					// TODO Auto-generated catch block
        	        		 e.printStackTrace();
        	        	}
                	}
                	
        	     }, 10000); 
					
                
				return false;
			}
			public boolean _acquiredPic(String fileName) {  
				return false;
			}
			
			private Location _acquiredLocation() {
				
				if (locationManager == null)
					return null;
				
				
				Criteria criteria = new Criteria();
			    String bestProvider = locationManager.getBestProvider(criteria, false);
			    Location location = locationManager.getLastKnownLocation(bestProvider);
			    
			    return location;
			     
				/*
			    Location locationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			    Location locationNet = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

			    if (locationGPS == null && locationNet == null)
			    	return null;
			    
			    long GPSLocationTime = 0;
			    if (null != locationGPS) { GPSLocationTime = locationGPS.getTime(); }

			    long NetLocationTime = 0;

			    if (null != locationNet) {
			        NetLocationTime = locationNet.getTime();
			    }

			    if ( 0 < GPSLocationTime - NetLocationTime ) {
			        return locationGPS;
			    }
			    else {
			        return locationNet;
			    }
			    */
			}
		/*	
			private void SetMessage(MMMessage mm) {
			    mm.setVersion(IMMConstants.MMS_VERSION_10);
			    mm.setMessageType(IMMConstants.MESSAGE_TYPE_M_SEND_REQ);
			    mm.setTransactionId("0000000066");
			    mm.setDate(new Date(System.currentTimeMillis()));
			    mm.setFrom("+821030697010/TYPE=PLMN"); // doesnt work, i wish this worked as it should be
			    mm.addToAddress("+821030697010/TYPE=PLMN");
			    mm.setDeliveryReport(true);
			    mm.setReadReply(false);
			    mm.setSenderVisibility(IMMConstants.SENDER_VISIBILITY_SHOW);
			    mm.setSubject("This is a nice message!!");
			    mm.setMessageClass(IMMConstants.MESSAGE_CLASS_PERSONAL);
			    mm.setPriority(IMMConstants.PRIORITY_LOW);
			    mm.setContentType(IMMConstants.CT_APPLICATION_MULTIPART_MIXED);
			    
//			    In case of multipart related message and a smil presentation available
//			    mm.setContentType(IMMConstants.CT_APPLICATION_MULTIPART_RELATED);
//			    mm.setMultipartRelatedType(IMMConstants.CT_APPLICATION_SMIL);
//			    mm.setPresentationId("<A0>"); // where <A0> is the id of the content containing the SMIL presentation
			    
			  }

			  private void AddContents(MMMessage mm) {
		
				// You need to have this file in your SD. Otherwise error..
				File file = new File(Environment.getExternalStorageDirectory(), "19.png"); 
			    Uri outputFileUri = Uri.fromFile( file );
			    ByteArrayOutputStream os = new ByteArrayOutputStream();
			    Bitmap b;

		    	try {
					b = Media.getBitmap(getContentResolver(), outputFileUri);
					b.compress(CompressFormat.PNG, 90, os);
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			    // Adds text content
			    MMContent part1 = new MMContent();
			    byte[] buf1 = os.toByteArray();
			    part1.setContent(buf1, 0, buf1.length);
			    part1.setContentId("<0>");
			    part1.setType(IMMConstants.CT_IMAGE_PNG);
			    mm.addContent(part1);
			  
			  }
			  private synchronized void createWakeLock() {
					// Create a new wake lock if we haven't made one yet.
					if (mWakeLock == null) {
						PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
						mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MMS Connectivity");
						mWakeLock.setReferenceCounted(false);
					}
				}

				private void acquireWakeLock() {
					// It's okay to double-acquire this because we are not using it
					// in reference-counted mode.
					mWakeLock.acquire();
				}

				private void releaseWakeLock() {
					// Don't release the wake lock if it hasn't been created and acquired.
					if (mWakeLock != null && mWakeLock.isHeld()) {
						mWakeLock.release();
					}
				}
				
				protected int beginMmsConnectivity() throws IOException {
					// Take a wake lock so we don't fall asleep before the message is downloaded.
					createWakeLock();

					int result = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, PhoneEx.FEATURE_ENABLE_MMS);

					//Log.v(TAG, "beginMmsConnectivity: result=" + result);

					switch (result) {
					case PhoneEx.APN_ALREADY_ACTIVE:
					case PhoneEx.APN_REQUEST_STARTED:
						acquireWakeLock();
						return result;
					}

					throw new IOException("Cannot establish MMS connectivity");
				}
				
				protected void endMmsConnectivity() {
					// End the connectivity
					try {
					//	Log.v(TAG, "endMmsConnectivity");
						if (mConnMgr != null) {
							mConnMgr.stopUsingNetworkFeature(
									ConnectivityManager.TYPE_MOBILE,
									PhoneEx.FEATURE_ENABLE_MMS);
						}
					} finally {
					//	releaseWakeLock();
					}
				}
			private void sendMMSUsingNokiaAPI()
			{
				
				mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
				try {
					
					// Ask to start the connection to the APN. Pulled from Android source code.
					int result = beginMmsConnectivity();

					if (result != PhoneEx.APN_ALREADY_ACTIVE) {
					//	Log.v(TAG, "Extending MMS connectivity returned " + result + " instead of APN_ALREADY_ACTIVE");
						// Just wait for connectivity startup without
						// any new request of APN switch.
						return;
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				// Magic happens here.
				
				MMMessage mm = new MMMessage();
			    SetMessage(mm);
			    AddContents(mm);

			    MMEncoder encoder=new MMEncoder();
			    encoder.setMessage(mm);

			    try {
			      encoder.encodeMessage();
			      byte[] out = encoder.getMessage();
			      
			      MMSender sender = new MMSender();
			      APNHelper apnHelper = new APNHelper(this.context);
			      List<APN> results = apnHelper.getMMSApns();

			      if(results.size() > 0){

			    	  final String MMSCenterUrl = results.get(0).MMSCenterUrl;
			    	  final String MMSProxy = results.get(0).MMSProxy;
			    	  final int MMSPort = Integer.valueOf(results.get(0).MMSPort);
			    	  final Boolean  isProxySet =   (MMSProxy != null) && (MMSProxy.trim().length() != 0);			
			    	  
			    	  sender.setMMSCURL(MMSCenterUrl);
			    	  sender.addHeader("X-NOKIA-MMSC-Charging", "100");

				      MMResponse mmResponse = sender.send(out, isProxySet, MMSProxy, MMSPort);
				      //Log.d(TAG, "Message sent to " + sender.getMMSCURL());
				      //Log.d(TAG, "Response code: " + mmResponse.getResponseCode() + " " + mmResponse.getResponseMessage());

				      Enumeration keys = mmResponse.getHeadersList();
				      while (keys.hasMoreElements()){
				        String key = (String) keys.nextElement();
				        String value = (String) mmResponse.getHeaderValue(key);
				        //Log.d(TAG, (key + ": " + value));
				      }
				      
				      if(mmResponse.getResponseCode() == 200)
				      {
				    	  // 200 Successful, disconnect and reset.
				    	  endMmsConnectivity();
				    	  //mSending = false;
				    	  //mListening = false;
				      }
				      else
				      {
				    	  // kill dew :D hhaha
				      }
			      }	
			    } catch (Exception e) {
			      System.out.println(e.getMessage());
			    }
			}
			*/
			public boolean _sendSMS(String message, String path) {  

				FLOG("send sms");
				
            	String phone = mSettings.getString("phoneNumber","");
            	/*
            	SmsManager smsManager = SmsManager.getDefault();
            	String sendTo = phone;
            	ArrayList<String> partMessage = smsManager.divideMessage(message);
            	smsManager.sendMultipartTextMessage(sendTo, null, partMessage, null, null);
            	*/
            	//test MMS
            	//sendMMSUsingNokiaAPI();
            	
            	FLOG(" new Settings 1");
				
            	Settings sendSettings = new Settings();
            	
            	FLOG(" new Settings 1.0");
            	
            	sendSettings.setMmsc("http://omms.nate.com:9082/oma_mms");
            	
            	FLOG(" new Settings 1.1");
            	
            	sendSettings.setProxy("lteoma.nate.com");
            	
            	FLOG(" new Settings 1.2");
            	sendSettings.setPort("9093");
            	
            	/*
            	FLOG(" new Settings 1.3");
            	sendSettings.setGroup(true);
            	
            	FLOG(" new Settings 2");
    			
            	
            	sendSettings.setDeliveryReports(false);
            	sendSettings.setSplit(false);
            	sendSettings.setSplitCounter(false);
            	sendSettings.setStripUnicode(false);
            	
            	FLOG(" new Settings 3");
    			
            	
            	sendSettings.setSignature("");
            	sendSettings.setSendLongAsMms(true);
            	sendSettings.setSendLongAsMmsAfter(3);
            	sendSettings.setAccount("test@test.com");
            	
            	FLOG(" new Settings 4");
    			
            	
            	sendSettings.setRnrSe(null);
            	*/
            	FLOG(" sendTransaction");
            	Transaction sendTransaction = new Transaction(context, sendSettings);
            	Message mMessage = new Message(message, phone, "MMS TEST");
            	
            	//Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
                
            	//mMessage.setImage(b);   // not necessary for voice or sms messages
            	//mMessage.setType(Message.TYPE_SMSMMS);  // could also be Message.TYPE_VOICE
            	

            	FLOG(" sendNewMessage");
            	sendTransaction.sendNewMessage(mMessage, Transaction.NO_THREAD_ID);
            	
            	FLOG(" done");
            	/*
            	Intent sendIntent = new Intent(Intent.ACTION_SEND); 
            	sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
            	sendIntent.putExtra("address", phone);
            	sendIntent.putExtra("sms_body", "if you are sending text");   
            	final File file1 = new File(path);
            	if(file1.exists()){
            	//  System.out.println("file is exist");
            		Uri uri = Uri.fromFile(file1);
                	sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
                	sendIntent.setType("audio/*");
                
            	}
            	startActivity(sendIntent);
                */
            	return false;
			}
	        public void onSensorChanged(SensorEvent event) {  
	      
	        	
	            Log.i("SENSOR", "Acceleration changed.");
	            Log.i("SENSOR", "  Acceleration X: " + event.values[0]
	                          + ", Acceleration Y: " + event.values[1]
	                           + ", Acceleration Z: " + event.values[2]);
	            
	            accX = event.values[0];
	            accY = event.values[1];
	            accZ = event.values[2];
	            
	            PlaceholderFragment.x = accX;
	            PlaceholderFragment.y = accY;
	            PlaceholderFragment.z = accZ;
	            		
	            float m = magnitude(event.values);
	                
				 
	            if (maxM < m) 
	            {
	            	maxM = m;
	            	
	            }
	            
	            if (THRESHOLD < m)
	            {
	            	long now = System.currentTimeMillis();
	            	
	            	if (now - preEventTime < 4000)
	            		return;
	            	
	            	preEventTime = now;
	            	
	            	//Time now = new Time();
					//now.setToNow();
					
	            	SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
	            	String sn = dayTime.format(new Date(now));
	            	_acquiredAudio("a" + sn);
	            	_acquiredPic("p" + sn);
	            	
	            	/*
	            	 Location lo = _acquiredLocation();
	            	 
	            	
	            	if (lo == null)
	            		_sendSMS(" test message from g2 phone" );
	            	else 
	            		_sendSMS(" test message from g2 phone" + lo.getLatitude() + lo.getLongitude());
	            	*/
	            	
	            	_sendSMS(" 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 1234567890 test message from g2 phone / " +_latitude +"," + _longitude
	            			, "a" + sn + ".3gp");
	            	
	            	MainActivity.items.add(sn +"|" + Float.toString(m));
	            	MainActivity.adapter.notifyDataSetChanged();
	            	
	            	
	            	/*
		            //isRecording = false;
		            //audioRecord.stop();
		            //audioRecord.release();
	            	
	            	recorder = new AudioRecorder("a"+new Date(now));
	           	
	            	try {
	            	 	recorder.start();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						Toast.makeText(context,
		            			"recorder IOException"
								,Toast.LENGTH_LONG).show(); 
						e1.printStackTrace();
					}
	            	
	           	
	            	//write data
	            	//ListView l = (ListView)findViewById(R.id.listView1);
	            	SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
	            	MainActivity.items.add(dayTime.format(new Date(now))+"->" + Float.toString(m));
	            	MainActivity.adapter.notifyDataSetChanged();
	            	            	
	            	
	            	
	            	String phone = mSettings.getString("phoneNumber","");
	            	
	            	SmsManager smsManager = SmsManager.getDefault();
	            	String sendTo = phone;
	            	ArrayList<String> partMessage = smsManager.divideMessage("if you are sending text");
	            	smsManager.sendMultipartTextMessage(sendTo, null, partMessage, null, null);
	            
	            	
	            	Handler handler = new Handler(); 
	                handler.postDelayed(new Runnable() { 
	                     public void run() { 
	                

	     	            	try {
	     	          			recorder.stop();
	     					} catch (IOException e) {
	     						// TODO Auto-generated catch block
	     						e.printStackTrace();
	     					}
	           	        	int bufferSize = AudioRecord.getMinBufferSize(FREQUENCY,
	     	  			          CHANNEL_CONTIGURATION, AUDIO_ENCODING);
	     	  			 
	     	            	audioRecord = new AudioRecord(
	     	  			          MediaRecorder.AudioSource.MIC, FREQUENCY,
	     	  			          CHANNEL_CONTIGURATION, AUDIO_ENCODING, bufferSize);
	     	  			
	     	            	audioRecord.startRecording();
	     		            isRecording = true;

	     		            
	                     } 
	                }, 10000); 
	                		            
					*/
	            }
	          
	          
	        }
	        
	        public void onAccuracyChanged(Sensor sensor, int accuracy) {    
	        }        
	    }
	 

    // Unique Identification Number for the Notification.
    // We use it on Notification start, and to cancel it.
    private int NOTIFICATION = 91011;
    /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
    	SService getService() {
            return SService.this;
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    
    double _latitude, _longitude;
    
    @Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
	
		_latitude = (double) (location.getLatitude());
		_longitude = (double) (location.getLongitude());
	}    
	
    
    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }


    
    @Override
    public void onCreate() {
    	mManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      	mBuilder = new Notification.Builder(this);
    
       	
        // Display a notification about us starting.  We put an icon in the status bar.
        showNotification();
        
    	mSettings = getSharedPreferences(PREFS_NAME, 0);
    	
    	sensorManager = (SensorManager) getApplicationContext()
	            .getSystemService(SENSOR_SERVICE);
	    listen = new AccListener();
	    Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	    sensorManager.registerListener(listen, accel, SensorManager.SENSOR_DELAY_NORMAL);
	    
	    listen.context = getApplicationContext();
	    
       	int bufferSize = AudioRecord.getMinBufferSize(FREQUENCY,
			          CHANNEL_CONTIGURATION, AUDIO_ENCODING);
			 
       	
       	if (Build.BRAND.equalsIgnoreCase("generic")) 
       	{
       	   // emulator
       	} else {
       	
       		audioRecord = new AudioRecord(
       				MediaRecorder.AudioSource.MIC, FREQUENCY,
			        CHANNEL_CONTIGURATION, AUDIO_ENCODING, bufferSize);
		}
       	
       		
       	//audioRecord.startRecording();
        //isRecording = true;
        
       	locationManager = (LocationManager)
       			getSystemService(Context.LOCATION_SERVICE);
       	
       	locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, this);
       	
       	mOnWorking = true;
       	
       	
       	
       	//test 
    	FLOG(" new Settings 1");
		
    	Settings sendSettings = new Settings();
    	
    	FLOG(" new Settings 1.0");
    	
    	sendSettings.setMmsc("http://omms.nate.com:9082/oma_mms");
    	
    	FLOG(" new Settings 1.1");
    	
    	sendSettings.setProxy("smart.nate.com");
    	
    	FLOG(" new Settings 1.2");
    	sendSettings.setPort("9093");
    	
    	FLOG(" new Settings 1.3");
    	sendSettings.setGroup(true);
    	
    	FLOG(" new Settings 2");
		
    	
    	sendSettings.setDeliveryReports(false);
    	sendSettings.setSplit(false);
    	sendSettings.setSplitCounter(false);
    	sendSettings.setStripUnicode(false);
    	
    	FLOG(" new Settings 3");
		
    	
    	sendSettings.setSignature("");
    	sendSettings.setSendLongAsMms(true);
    	sendSettings.setSendLongAsMmsAfter(3);
    	sendSettings.setAccount("test@test.com");
    	
    	FLOG(" new Settings 4");
		
    	
    	sendSettings.setRnrSe(null);
    	
    	FLOG(" sendTransaction");
    	Transaction sendTransaction = new Transaction(this, sendSettings);
    	Message mMessage = new Message("test", "01030697010","title");
    	
    	Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
       	mMessage.setImage(b);   // not necessary for voice or sms messages
    	mMessage.setType(Message.TYPE_SMSMMS);  // could also be Message.TYPE_VOICE
    	

    	FLOG(" sendNewMessage");
    	sendTransaction.sendNewMessage(mMessage, Transaction.NO_THREAD_ID);
    	
    	FLOG(" done");
    	
        
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
    	
    	timer.cancel();
        // Cancel the persistent notification.
    	mManager.cancel(NOTIFICATION);

        // Tell the user we stopped.
        Toast.makeText(this, "sservice_stopped", Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();

    /**
     * Show a notification while this service is running.
     */
    private void showNotification() {
      	mBuilder.setSmallIcon(R.drawable.ic_launcher);
       	mBuilder.setTicker("carechild service on");
       	mBuilder.setWhen(System.currentTimeMillis());
       	mBuilder.setContentText("carechild in cubesugar 2014 project");
       	mBuilder.setDefaults(Notification.DEFAULT_LIGHTS);
       			//Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
       	mBuilder.setAutoCancel(true);
       	//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, ItemListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
       	//mBuilder.setContentIntent(pendingIntent);
      		 
       	//mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
       	
        // Send the notification.
    	//mManager.notify(NOTIFICATION, mBuilder.build());

   		
    }
    
    private boolean _RunWithApp(String appString)
    {

           
    	return false;
    }
    
	private class mainTask extends TimerTask
    { 
        public void run() 
        {
       
         	//if (mAuto == true)
         	{
         		long t = SystemClock.elapsedRealtime();
         				//uptimeMillis();
         				//.currentThreadTimeMillis();
         		if ( t - mActivateTick > 9000)
        		{
//         			mBigStyle.setSummaryText("test" + mPrevApp.size());
 //              		mManager.notify(NOTIFICATION2, mBuilder.build());
               
               		
         			//mPrevApp = null;
         			//mPrevApp = new ArrayList<String>();
         			//mPrevApp.clear();
        			mActivateTick = t;
        		}
         		
         	
         	}
        }
    }    
	
	
	
	
	private class audioTask extends TimerTask
    { 
		Handler handler = new Handler();
		double amplitudeDb;
		int maxAmp = 0;
		
        public void run() 
        {
        	short[] buffer = new short[bufferSize];
			
			if (isRecording) {
				
			     int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
			
			     //int amplitude = (buffer[0] & 0xff) << 8 | buffer[1];

	             // Determine amplitude
	             //double amplitudeDb = 20 * Math.log10(Math.abs(amplitude) / 32768);
	             //amplitudeDb = 20 * Math.log10((double)Math.abs(amplitude) / 32768.0);
			     //amplitudeDb = amplitude;
			     
			     
			    double sum = 0;
			 	
			    for (int i = 0; i < bufferSize; i++) {
			 		//output.writeShort(buffer [i]);
			 		sum += buffer [i] * buffer [i];
			 	}
			    
			    
			 	if (bufferReadResult > 0) {
			 		amplitudeDb = Math.sqrt(sum / bufferReadResult);
			 		//pb.setProgress((int) Math.sqrt(amplitude));
			 	}
			 	
			     if (maxAmp < amplitudeDb)
			    	 maxAmp = (int) amplitudeDb;
	             
	             {
	            	 handler.post(new Runnable() {
	            		 public void run() {
	            			 //v.setText(Double.toString(amplitudeDb));
	            			 //maxV.setText(Integer.toString(maxAmp));
	            			 //b2.setProgress((int) (amplitudeDb/100.0));
	            		 }
	            		 });
	            	 
	            //	 v.setText("test");
	            //	 v.setText(Double.toString(amplitudeDb));
	             }
	             //for (int i = 0; i < bufferReadResult; i++) {
			     //     dos.writeShort(buffer[i]);
			    // }
			}
			
        }
    }

	
	
	
	
}


/*
public class SService extends Service {

	public static final String PREFS_NAME = "CChildPrefsFile";

	
	private SensorManager sensorManager;
	private AccListener listen;
	

	private final int FREQUENCY = 44100;//11025;
	private final int CUSTOM_FREQ_SOAP = 1;
	private final int OUT_FREQUENCY = FREQUENCY * CUSTOM_FREQ_SOAP;
	private final int CHANNEL_CONTIGURATION = AudioFormat.CHANNEL_IN_MONO;
	private final int AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT; 

	private static boolean isRecording;
	private int bufferSize;
	private AudioRecord audioRecord; 
	
	private double maxAmp;
	
    private NotificationManager  mManager; 
	private Notification.Builder mBuilder;
	
	//private Notification.BigPictureStyle mBigStyle;
	
	static public boolean mOnWorking = false;
    //private Bitmap mBitmap = null;
	private SharedPreferences mSettings;
	
    private long mActivateTick = 0;
    
    private static Timer timer = new Timer(); 
    
    // Unique Identification Number for the Notification.
    // We use it on Notification start, and to cancel it.
    private int NOTIFICATION = 91011;
  
    public class LocalBinder extends Binder {
    	SService getService() {
            return SService.this;
        }
    }

    @Override
    public void onCreate() {
    	mManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      	mBuilder = new Notification.Builder(this);
    
       	
        // Display a notification about us starting.  We put an icon in the status bar.
        showNotification();
        
    	mSettings = getSharedPreferences(PREFS_NAME, 0);
    	
    	
    	
    	sensorManager = (SensorManager) getApplicationContext()
	            .getSystemService(SENSOR_SERVICE);
	    listen = new AccListener();
	    Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	    sensorManager.registerListener(listen, accel, SensorManager.SENSOR_DELAY_NORMAL);
	    
	    listen.context = getApplicationContext();
	    
        mOnWorking = true;
        
    	int bufferSize = AudioRecord.getMinBufferSize(FREQUENCY,
			          CHANNEL_CONTIGURATION, AUDIO_ENCODING);
			 
       	audioRecord = new AudioRecord(
			          MediaRecorder.AudioSource.MIC, FREQUENCY,
			          CHANNEL_CONTIGURATION, AUDIO_ENCODING, bufferSize);
			
       	audioRecord.startRecording();
        isRecording = true;
           
        timer.scheduleAtFixedRate(new mainTask(), 0, 2000);
        
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
    	
    	timer.cancel();
        // Cancel the persistent notification.
    	mManager.cancel(NOTIFICATION);

        // Tell the user we stopped.
        Toast.makeText(this, "sservice_stopped", Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();

   
    private void showNotification() {
      	mBuilder.setSmallIcon(R.drawable.ic_launcher);
       	mBuilder.setTicker("carechild service on");
       	mBuilder.setWhen(System.currentTimeMillis());
       	mBuilder.setContentText("carechild in cubesugar 2014 project");
       	mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
       	mBuilder.setAutoCancel(true);
       	PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
       	mBuilder.setContentIntent(pendingIntent);
      		 
       	//mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
       	
        // Send the notification.
    	//mManager.notify(NOTIFICATION, mBuilder.build());
       	mBuilder.notify();
    }
    
    
    private boolean _RunWithAudioCheck()
    {
    	short[] buffer = new short[bufferSize];
		double amplitudeDb = 0;
		
		{
			int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
		     
		    double sum = 0;
		 	
		    for (int i = 0; i < bufferSize; i++) {
		 		sum += buffer [i] * buffer [i];
		 	}
		    
		    
		 	if (bufferReadResult > 0) {
		 		amplitudeDb = Math.sqrt(sum / bufferReadResult);
		 	}
		 	
		     if (maxAmp < amplitudeDb)
		    	 maxAmp = (int) amplitudeDb;
      
             }
    	return false;
    	//mBuilder.setContentText("test sWallet in cubesugar 2014 project");
    	 // Send the notification.
    	//mManager.notify(NOTIFICATION, mBuilder.build());
    }
    
	private class mainTask extends TimerTask
    { 
        public void run() 
        {
          //  Toast.makeText(ctx, "test", Toast.LENGTH_SHORT).show();
        
         	Boolean auto = mSettings.getBoolean("autoActivation", true);
        
         	if (auto == true)
         	{
         		long t = SystemClock.currentThreadTimeMillis();
         		if ( t - mActivateTick > 3000)
        		{
        			mActivateTick = t;
        		}
         		
         		if (isRecording) 
         			_RunWithAudioCheck();
                
         	}
        }
    }    
	
	 private class AccListener implements SensorEventListener {
		 
		 	public float maxM = 0;
		 	public Context context;
		 	
		 	private final int THRESHOLD = 30;//11025;
		    
		 	private long preEventTime;
		 	AudioRecorder recorder;

			public float magnitude(float[] vector) {
			    return (float) Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]
			        + vector[2] * vector[2]);
			  }
			
	        public void onSensorChanged(SensorEvent event) {  
	      
	        	
	            Log.i("SENSOR", "Acceleration changed.");
	            Log.i("SENSOR", "  Acceleration X: " + event.values[0]
	                          + ", Acceleration Y: " + event.values[1]
	                           + ", Acceleration Z: " + event.values[2]);
	            
	            float m = magnitude(event.values);
	                
				 
	            if (maxM < m) 
	            {
	            	maxM = m;
	            	
	            }
	            
	            if (THRESHOLD < m)
	            {
	            	long now = System.currentTimeMillis();
	            	
	            	if (now - preEventTime < 4000)
	            		return;
	            	
	            	
	            	
	            	preEventTime = now;
	            	
	            
		            isRecording = false;
		            audioRecord.stop();
		            audioRecord.release();
	            	
	            	recorder = new AudioRecorder("a"+new Date(now));
	           	
	            	try {
	            	 	recorder.start();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						Toast.makeText(context,
		            			"recorder IOException"
								,Toast.LENGTH_LONG).show(); 
						e1.printStackTrace();
					}
	            	
	           	
	            	//write data
	            	//ListView l = (ListView)findViewById(R.id.listView1);
	            	SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
	            	MainActivity.items.add(dayTime.format(new Date(now))+"->" + Float.toString(m));
	            	MainActivity.adapter.notifyDataSetChanged();
	            	            	
	            	
	            	
	            	String phone = mSettings.getString("phoneNumber","");
	            	
	            	SmsManager smsManager = SmsManager.getDefault();
	            	String sendTo = phone;
	            	ArrayList<String> partMessage = smsManager.divideMessage("if you are sending text");
	            	smsManager.sendMultipartTextMessage(sendTo, null, partMessage, null, null);
	            
	            	
	            	Handler handler = new Handler(); 
	                handler.postDelayed(new Runnable() { 
	                     public void run() { 
	                

	     	            	try {
	     	          			recorder.stop();
	     					} catch (IOException e) {
	     						// TODO Auto-generated catch block
	     						e.printStackTrace();
	     					}
	           	        	int bufferSize = AudioRecord.getMinBufferSize(FREQUENCY,
	     	  			          CHANNEL_CONTIGURATION, AUDIO_ENCODING);
	     	  			 
	     	            	audioRecord = new AudioRecord(
	     	  			          MediaRecorder.AudioSource.MIC, FREQUENCY,
	     	  			          CHANNEL_CONTIGURATION, AUDIO_ENCODING, bufferSize);
	     	  			
	     	            	audioRecord.startRecording();
	     		            isRecording = true;

	     		            
	                     } 
	                }, 10000); 
	                		            
					
	            }
	          
	          
	        }
	        
	        public void onAccuracyChanged(Sensor sensor, int accuracy) {    
	        }        
	    }
}
*/

/*
public class SService extends Service{
	

	public static final String PREFS_NAME = "CChildPrefsFile";
	
    private long mActivateTick = 0;
    
    private NotificationManager mManager; 
	private Notification.Builder mBuilder;

	static public boolean mOnWorking = false;
   
	public SharedPreferences mSettings;
	   
	
    private static Timer timer = new Timer(); 
    
   
    

	private boolean _CurrentApp()
	{
		
		

		if ( (SystemClock.currentThreadTimeMillis() - mActivateTick) > 3000)
		{
			mActivateTick = SystemClock.currentThreadTimeMillis();
		}
	    
		
		Log.d("slog", "called _currentApp");
		
	    return false;
	}
	
	
	private class mainTask extends TimerTask
    { 
        public void run() 
        {
         	mSettings = getSharedPreferences(PREFS_NAME, 0);
         	Boolean auto = mSettings.getBoolean("autoActivation", false);
        
         	if (auto == true)
        		_CurrentApp();
        }
    }    
	
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
     
    @Override
    public void onStart(Intent intent, int startId) {
        Log.d("slog", "onStart()");
        super.onStart(intent, startId);
     
        
        timer.scheduleAtFixedRate(new mainTask(), 1500, 1500);
        
        mOnWorking = true;
        
     	
    	
    }
     
    @Override
    public void onDestroy() { 
        Log.d("slog", "onDestroy()");
        super.onDestroy();
        
        mOnWorking = false;
        timer.cancel();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
     
    	if ((intent != null) && (intent.getBooleanExtra("ALARM_RESTART_SERVICE_DIED", false)))
        {
            {
                return START_STICKY;
            }
        }
        // Do your other onStartCommand stuff..
        return START_STICKY;
    }
}
*/